﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using SimpleJson;
using Pomelo.DotNetClient;
public class LoginUI : MonoBehaviour {

    private string openid = "oeHmys0RRebCF8pgYXjpXT2JEgoU";
    private string acccess_token = "360Zxw4t8PALo6wJHUvihDQ1_VQlkbWPKG-t0RHccSoblQ0FxWFfnL6gz6KevFeXiAKf366HPKVtpoolVuzPJF312Gh7xxeFGlzWEieco6A";
    //public string refress_token = "360Zxw4t8PALo6wJHUvihDqv1tRKC_uiFlLvcKxPiq1X3ePcICCcIWUYmNDaNibwbOOEp5i9nxdjJ";
    public  PomeloClient pc;
    
    //用于 握手的key  
    public static string HandShakeKey = "agashgw123pajloaxn34ga8xrunpagkjwlaw456xnpaagl29w4rxn";
	// Use this for initialization
	void Start () {
        //Application.targetFrameRate = 60;
        //robot.host = "119.23.153.59";
        login();
	}

    int count = 1;
    public void Click()
    {
        int t = 40;
        StartCoroutine(CreateItems(t));
        //while(count-- > 0)
        //Invoke("Click", 1f);
    }

    IEnumerator CreateItems(int t)
    {
        while (t-- > 0)
        {
            int c = 1;
            while (c-- > 0)
            {
                GameObject nobj = new GameObject();
                var ret = nobj.AddComponent<robot>();
                ret.CreateGame();
            }
            yield return null;
            yield return null; yield return null; yield return null;
            yield return null;
            yield return null;
            yield return null;
            yield return null;
            yield return null;
            yield return null; yield return null; yield return null;
            yield return null;
            yield return null;
            yield return null;
            yield return null;
        }
    }

    public void login()
    {
        //string host = "119.23.153.59";
        //int port = 7821;
        string host = "119.23.147.18";
        int port = 8921;
        pc = new PomeloClient();


        pc.initClient(host, port, () => { 
        pc.NetWorkStateChangedEvent += (state) =>
        {
            Console.WriteLine("net change : " + state);
        };
        JsonObject shakemsg = new JsonObject();
        shakemsg["key"] = HandShakeKey;
        string str = "bt_108";// +Mathf.Floor(UnityEngine.Random.value * 99999);
        //0.握手的时候 带上 这个key， 不带的话我这边就会跑去链接
        pc.connect(shakemsg, (data) =>
        {
            Debug.Log("connection compelete" + data);
            JsonObject msg = new JsonObject();
            //msg["openid"] = openid;
            //msg["access_token"] = acccess_token;
            //msg["openid"] = str;
            //msg["access_token"] = "robot_immunity";
            msg["key"] = str;
            msg["type"] = 2;
            // 1. platform server 用户登入  登入后返回  
            //{"code":0,"uid":10000,"token":"99ce344a8b7c2fe5c3b3f416f5fa3cade8e2fe44bfa37a045fb53358f72ddf0f","host":"127.0.0.1","port":3010}
            pc.request("platform.platformHandler.HHAuthor", msg, OnQuery);
        });
        });
    }
    void OnQuery(JsonObject result)
    {
        Debug.Log(result);
        if (Convert.ToInt32(result["code"]) == 0)
        {
            pc.disconnect();

            string host = (string)result["host"];
            int port = Convert.ToInt32(result["port"]);
            pc = new PomeloClient();
            pc.initClient(host, port);
            JsonObject shakemsg = new JsonObject();
            shakemsg["key"] = HandShakeKey;
            //同样带上key
            pc.connect(shakemsg, (data) =>
            {
                Debug.Log("connection compelete" + data);
                JsonObject msg = new JsonObject();
                msg["uid"] = result["uid"];
                msg["token"] = result["token"];
                //2. connector登入操作 返回用户信息
                //{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"127.0.0.1","cardNum":8}
                pc.request("connector.hhuserHandler.Login", msg, OnLogin);


            });
            pc.on("OnMessage", (gmsg) =>
            {
                Debug.Log("OnMessage:" + gmsg);
            });

#region update 20 16 11 07
            //监控网络状态
            pc.NetWorkStateChangedEvent += (state) =>
            {
                Console.WriteLine("net change : " + state);
            };


            //{"cardNum":8} 自己房卡数量发生变化更新
            pc.on("OnCardUpdate", (gmsg) =>
            {
                Debug.Log("OnCardUpdate:" + gmsg);
            });
            /*
             * 退出出房间，
             * 所有退出房间都用这个，
             * 游戏开始后，点击即会出现投票推出框。
             * 
             * 游戏未开始，非房主会直接退出。
             * 
             * 房主则会立刻解散房间。
             */
            JsonObject arg = new JsonObject();
            pc.request("game.roomHandler.leaveRoom", arg, (sret) =>
            {
                Debug.Log("Leavel" + sret);
            });

            /*
             * 有其它玩家加入房间
             * 数据结构如下,idx指明在房间的哪个位置
             * {"uid":10390,"idx":3,"ready":0,"info":{"uid":10390,"name":"robot_10002","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"127.0.0.1"}}
             */
            pc.on("OnAdd", (gmsg) =>
            {
                Debug.Log("OnAdd:" + gmsg);
            });

            /*有玩家离开了房间
             * 数据结构如下， idx为 1的玩家离开了房间
             * {idx: 1}
             */
            pc.on("OnLeave", (gmsg) =>
            {
                Debug.Log("OnLeave:" + gmsg);
            });

            //{"room":0} 房间被关闭的时候，自己的房间id设置成0，玩家自己退出或者房间被解散
            pc.on("OnRoomClose", (gmsg) =>
            {
                Debug.Log("OnRoomClose:" + gmsg);
            });
            //申请解散房间的内容
            /*
             *{1:0, 1:0, 2:1, 3: 2}  0,1,2分别表示  未知，拒绝  同意
             *
             *更新也是调用这个
             *
             */
            pc.on("OnChoose", (gmsg) =>
            {
                Debug.Log("OnChoose:" + gmsg);
            });
            /* 申请解散的窗口关闭
             *  无数据
             */
            pc.on("OnChooseClose", (gmsg) =>
            {
                Debug.Log("OnChoose:" + gmsg);
            });
            /*
             * 返回房间的update信息，断线重连使用
             * {
             *   level: 5 当前打到第5局
             *   closer:{1:0, 1:0, 2:1, 3: 2}  同上面的OnChoose 
             * }
             */
            pc.request("game.roomHandler.getRoomUpdate", arg, (sret) =>
            {
                Debug.Log("getRoomUpdate" + sret);
            });
            /*
             * 返回房间的update信息， 完全断开后的返回  痛create room 、 join room
             * {
             *   level: 5 当前打到第5局
             *   closer:{1:0, 1:0, 2:1, 3: 2}  同上面的OnChoose 
             * }
             */
            pc.request("game.roomHandler.getRoomInfo", arg, (sret) =>
            {
                Debug.Log("getRoomUpdate" + sret);
            });
#endregion
        }
    }

    public enum OperationResult{
	        None= 1,
	        Play= 2,
	        Peng= 4,
	        MingGang= 8,
	        DianGang= 16,
	        AnGang= 32,
	        CHI= 64,
	        Hu= 128,
	        Draw= 256 
        };
    public enum HuFa
    {
        zimo = 1,
	    duiduihu = 2,
	    qidui = 4,
	    siguihupai = 8,
	    hunyise = 16,
	    hundui = 32,
	    qingyise = 64,
	    qingdui = 128,
	    wuguijiabei = 256,
	    yaojiu = 512,
	    quanyao = 1024,
	    shisan = 2048,
	    quanfeng = 4096,
	    chihu = 8192,
	    haidi = 16384,
	    qiang = 32768,
        gangbao = 65536,    //杠爆
        zanpai = 131072,    //沾牌
        quanbao = 262144    //全包
    };

    public string rid = "";

    public object[] EncodeToInt(byte[] bytes)
    {
        int len = (int)((bytes.Length+3)/4);
        object[] arr = new object[len + 1];
        arr[0] = bytes.Length;
        for(int i=0; i<arr.Length-1; i++)
        {
            if (i * 4 + 4 > bytes.Length)
            {
                byte[] tmp = new byte[] { 0,0,0,0};
                int k = 0;
                for (int j = i * 4; j < bytes.Length; j++)
                {
                    tmp[k++] = bytes[j];
                }
                arr[i + 1] = System.BitConverter.ToInt32(tmp, 0);
            }
            else
            {
                arr[i + 1] = System.BitConverter.ToInt32(bytes, i * 4);
            }
        }
        return arr;
    }

    public byte[] DecodeToByte(object[] data)
    {
        int dataLen = (int)data[0];
        int count = 0;
        byte[] bytes = new byte[dataLen]; 
        for (int i = 1,len = data.Length; i < len; i++)
        {
            byte[] tmp = System.BitConverter.GetBytes((int)data[i]);

            for (int j = 0; j < tmp.Length && j+count<dataLen; j++ )
            {
                bytes[j + count] = tmp[j];
            }
            count += tmp.Length;
        }
        return bytes;
    }
    public enum WanFa
    {
        meiwan = 1,
        meibing = 2,
        meisuo = 4,
        meizi = 8,
        qianggang = 16,
        qianggangquanbao = 32,
        gangbaoquanbao = 64,
        zanpaiquanbao = 128,
        genpai = 256,
        yijiuwan = 512
    }

    public void SendGm(string p1, string p2, string p3, string p4,string cards)
    {
        var jjobj = new JsonObject();
        jjobj["p1"] = p1;
        jjobj["p2"] = p2;
        jjobj["p3"] = p3;
        jjobj["p4"] = p4;
        jjobj["card"] = cards;
        if(robot.last != null)
        {
            robot.last.pc.request("connector.userHandler.WriteFile", jjobj, (ret) =>
            {
                Debug.Log("WriteFile" + ret);

            });
        }

    }
    void OnLogin(JsonObject result)
    {
        Debug.Log(result);
        JsonObject msg = new JsonObject();
        //获取用户信息
        pc.request("connector.userHandler.getUserInfo", msg, (ret) =>
        {
            Debug.Log("getUserInfo" + ret);
        });

        pc.request("connector.hhuserHandler.Share", msg, (ret) =>
        {
            Debug.Log("Share" + ret);
        });
        //获取用户  更新信息，断线后重连使用
        /* 
           只返回会更新的用户信息，如
         *{room: 0, cardNum: 8}
         *房间号为0 玩家不在房间
         *身上房卡 8张
         */
        pc.request("connector.userHandler.getUserUpdate", msg, (ret) =>
        {
            Debug.Log("getUserUpdate" + ret);
        });

        //获取自己的录像列表  返回{"data":[{"rid":1000096,"room":100001，"date":1480153867133,"players":[{"name":"robot_72077","uid":10791},{"name":"robot_10000","uid":10388},{"name":"robot_10001","uid":10389},{"name":"robot_10002","uid":10390}]}]}
        pc.request("connector.userHandler.getUserRecords", msg, (ret) =>
        {
            Debug.Log("getUserRecords" + ret);
        });
        pc.request("connector.userHandler.getPublicMessage", msg, (ret) =>
        {
            Debug.Log("getPublicMessage" + ret);
        });
        //观看某场录像，可以看任何的录像 只要输入id
        msg["rid"] = "1001860";
        pc.request("connector.userHandler.getRecord", msg, (ret) =>
        {
            Debug.Log("getRecord" + ret);
        });

        //msg["invitecode"] = "86492";
        //pc.request("connector.hhuserHandler.Intive", msg, (ret) =>
        //{
        //    Debug.Log("Intive" + ret);
        //    msg["productid"] = "1";
        //    pc.request("connector.hhuserHandler.Order", msg, (gret) =>
        //    {
        //        Debug.Log("Order" + gret);
        //    });

        //});

        //pc.request("connector.hhuserHandler.GetProduct", msg, (gret) =>
        //{
        //    Debug.Log("GetProduct" + gret);
        //});

        //JsonObject talk = new JsonObject();
        //string strName = System.IO.File.ReadAllText("F:/Temp/1.txt");
        //byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strName);
        ////byte[] news =  DecodeToByte(EncodeToInt(bytes));

        ////int[] arr = EncodeToInt(bytes);

        //talk["msg"] = new List<object>(EncodeToInt(bytes));
        //pc.request("game.chatHandler.sendBytes", talk, (sret) =>
        //{
        //    Debug.Log("sendBytes：" + sret);
        //});
        //pc.on("OnChatBytes", (gmsg) =>
        //{
        //    object[] arr = ((List<object>)gmsg["msg"]).ToArray();
        //    byte[] bts = DecodeToByte(arr);
        //    Debug.Log(System.Text.Encoding.UTF8.GetString(bts));
        //    Debug.Log("OnChatBytes:" + gmsg);
        //});
        //pc.request("connector.userHandler.joinRoom", msg, (ret) =>
        //{
        //    Debug.Log(ret);

        //});

        pc.on("OnChat", (gmsg) =>
        {
            Debug.Log("OnChat:" + gmsg);
        });
        msg["cost"] = 1;
        msg["opt"] = new JsonObject();
        JsonObject opt = msg["opt"] as JsonObject;
        opt["type"] = 7; //1 鸡胡 2 100张
        opt["ma"] = 6; // 0 2 4 6
        opt["gui"] = 1; // 0 无鬼 1白板做鬼 
        opt["in"] = 1;
        opt["aa"] = 1;
        opt["wanfa"] = WanFa.meizi;//WanFa.meiwan | WanFa.genpai | WanFa.qianggang | WanFa.qianggangquanbao | WanFa.gangbaoquanbao | WanFa.zanpaiquanbao | WanFa.yijiuwan; //跟牌 0 1
        opt["hufa"] = HuFa.shisan | HuFa.quanbao | HuFa.quanfeng | HuFa.quanyao | HuFa.qingyise;
        pc.on("OnRoomInfo", (gmsg) =>
        {
            Debug.Log("OnRoomInfo:" + gmsg);
        });
        pc.on("OnGroupInfo", (gmsg) =>
        {
            Debug.Log("OnGroupInfo:" + gmsg);
        });
        JsonObject aarg = new JsonObject();
        //aarg["close"] = 1;
        //pc.request("game.roomHandler.leaveRoom", aarg, (sret) =>
        //{
        //    print("Leave" + sret);
        //});
       //创建房间
        pc.request("connector.userHandler.createGroupRoom", msg, (vret) =>
        {
            Debug.Log(vret);
            JsonObject arg = new JsonObject();
            arg["rid"] = vret["id"];
            rid = vret["id"] as string;
            //CreateOther(vret["id"] as string);
            //加入房间
           
            /*
             * 返回房间信息，
             * 主要有 id  房价id
             * opt  属性
             * users 玩家数组[]
             *      玩家信息 uid  玩家id
             *               idx  玩家编号！在游戏里面都是用这个来描述。0，1,2,3分别表示 房主，然后逆时针的三个玩家。这里需要判断uid跟自己的uid一样，那么用那个idx请求
             *               info  头像ip等信息
             {"id":105000,"opt":{"ma":6,"gui":1,"qidui":1,"qiang":1,"qupai":16,"quanbao":6,"xuangui":false},"users":[{"uid":10000,"idx":0,"info":{"name":"3D Coffice","sex":1,
             * "head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}},{"uid":10000,"idx":1,"info":{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}},{"uid":10000,"idx":2,"info":{"name":"3D Coffice","sex":1,"head":"http://wx.qlogo.cn/mmopen/PiajxSqBRaEIrZyEsQIv1C5Uxiac0wicaICWticoLSCc4IVTIg4gegs5a4TicI79Zk35CrqVXILIkFibDwjRHcPjn9hQ/0","ip":"192.168.11.186"}}]}
             
             */
            //pc.request("game.roomHandler.getRoomUpdate", arg, (sret) =>
            //{
            //    Debug.Log("getRoomUpdate" + sret);
            //});

            //pc.request("game.roomHandler.getRoomInfo", arg, (sret) =>
            //{
            //    Debug.Log("getRoomUpdate" + sret);
            //});
            DateTime begin = System.DateTime.Now;

           // arg["close"] = 1;
            pc.request("game.roomHandler.leaveRoom", arg, (sret) =>
            {
                DateTime now = System.DateTime.Now;
                Debug.Log((now - begin).TotalMilliseconds);
                Debug.Log("Leave" + sret);
            });

            //{"room":0} 房间被关闭的时候，自己的房间id设置成0，玩家自己退出或者房间被解散
            pc.on("OnRoomClose", (gmsg) =>
            {
                Debug.Log("OnRoomClose:" + gmsg);
                DateTime now = System.DateTime.Now;
                Debug.Log((now - begin).TotalMilliseconds);
            });
            //pc.request("connector.userHandler.joinRoom", arg, (ret) =>
            //{
            //    Debug.Log(ret);

            //});

            pc.on("OnAdd", (gmsg) =>
            {
                Debug.Log("OnAdd:" + gmsg);
            });

            pc.on("OnLeave", (gmsg) =>
            {
                Debug.Log("OnLeave:" + gmsg);
            });

            pc.on("OnClose", (gmsg) =>
            {
                Debug.Log("OnClose:" + gmsg);
            });

            pc.on("OnAgree", (gmsg) =>
            {
                Debug.Log("OnAgree:" + gmsg);
            });
            /*
             {"host":0,"gui":33,"remain":3,"players":[{"card":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000},{"card":13,"his":[],"heap":[],"score":1000}]}
             
             * 前言 牌0-33 依次表示  1-9 万  1-9饼  1-9条  字
             * 
             * host 庄家
             * gui  -1是无鬼
             * remain 剩余卡牌
             * players 玩家数组:
             *          card 手牌 其它人的手牌未知，只有张数
             *          his  已经出的牌
             *          heap [{t:0,v:1}]等于旁边的牌 t 0 1 2 3 碰 点杠 明杠 暗杠 v值
             *          score 分数
             */
            pc.on("OnStart", (gmsg) =>
            {
                Debug.Log("Start:" + gmsg);
            });

            /*广播  玩家idx补一张牌
             * 其它的玩家收到的是
             * idx为0的哥们补了一张牌
             * {"idx":0}
             * 
             * Draw:{"idx":0,"val":4}
             * 
             */
            pc.on("OnDraw", (gmsg) =>
            {
                Debug.Log("Draw:" + gmsg);
            });


            /* 单独请求你，要求你出牌
               op 类型位运算的组,看上面的OperationResult   OperationResult.Hu|OperationResult.AnGang|OperationResult.None 就是同时可以胡也可以暗杠,也可以不出
               val 宣传就是牌值
             */
            pc.on("OnCall", (gmsg) =>
            {
                Debug.Log("Call:" + gmsg);
                return;
                msg = new JsonObject();
                msg["op"] = (int)OperationResult.Hu;
                msg["val"] = 0;
                /*
                 从上面的op 里面选 一种操作op
                 */
                pc.request("game.gameHandler.operation", msg, (ret) =>
                {
                    Debug.Log(ret);
                });
            });

            /*
             op val 就是上面操作的通知，通知所有玩家
             */
            pc.on("OnPlay", (gmsg) =>
            {
                Debug.Log("Play:" + gmsg);
            });
            /*
             {"ma":[0,16,13,22,30,0],"players":[{"card":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"his":[],"heap":[],"score":1006},{"card":[33,1,4,6,8,10,13,17,18,19,20,22,23],"his":[],"heap":[],"score":998},{"card":[33,3,9,9,10,14,19,22,24,26,26,27,29],"his":[],"heap":[],"score":998},{"card":[2,3,4,9,14,18,21,21,23,23,25,27,29],"his":[],"heap":[],"score":998}],"hu":{"0":{"mutil":2,"way":1,"cards":[0,0,0,1,1,1,2,2,2,3,3,3,4,4],"guiIdx":[],"zhong":[0,2,3,5]}}}
             游戏结算的通知
             *   ma  开的六章马牌
             *   players 玩家的游戏数据
             *   hu  胡的信息，里面可能有多个玩家一起胡
             *      mutil 倍率
             *      way  胡法   1<<n 位运算的方式表示
             *      cards 胡牌的队列 
             *      guiIdx 数组 表示上面card里面的idx是鬼变的 类似的cards[0, 1, 1, 1, 0], guiidx [2, 3] 里面的 2 、3位置的1是鬼变的
             *      zhong  中码，自己中码的信息 如[0,2,3,5],就是中了ma[0] ma[2] ma[3] ma[5]
             */
            pc.on("OnEnd", (gmsg) =>
            {
                Debug.Log("end:" + gmsg);
            });
        });


    }
	// Update is called once per frame
	void Update () {
       // Debug.Log(System.DateTime.UtcNow.TotalMilliseconds);
	}
}
